<template>
	<view>
		<canvas id="qrcode" canvas-id="qrcode" style="width: 150px;height:150px;" />
	</view>
</template>

<script setup>
	import UQRCode from 'uqrcodejs';
	import {defineExpose} from 'vue'
	
	/**
	 * 生成二维码
	 * 文档地址：https://uqrcode.cn/doc/
	 */
	const genQr = (data)=>{
		const qr = new UQRCode();
		qr.data = data;
		qr.size = 150;
		qr.backgroundImageBorderRadius=10;
		qr.foregroundColor =  "#324a31"
		qr.make();
		// 组件内调用需传this，vue3 中 this 为 getCurrentInstance()?.proxy
		const ctx = uni.createCanvasContext('qrcode', this); 
		qr.canvasContext = ctx;
		qr.foregroundImageSrc = '/static/logo.png';
		
		// 调用制作二维码方法
		qr.drawCanvas();
		
		draw(qr)
	}
	
	function draw(qr){
		var drawModules = qr.getDrawModules();
		// 遍历drawModules创建dom元素
		var qrHtml = '';
		for (var i = 0; i < drawModules.length; i++) {
			var drawModule = drawModules[i];
			switch (drawModule.type) {
			case 'tile':
				/* 绘制小块 */
				qrHtml += `<div style="position: absolute;left: ${drawModule.x}px;top: ${drawModule.y}px;width: ${drawModule.width}px;height: ${drawModule.height}px;background: ${drawModule.color};"></div>`;
				break;
			case 'image':
				/* 绘制图像 */
				qrHtml += `<img style="position: absolute;left: ${drawModule.x}px;top: ${drawModule.y}px;width: ${drawModule.width}px;height: ${drawModule.height}px;" src="${drawModule.imageSrc}" />`;
				break;
			}
		}
		document.getElementById('qrcode').innerHTML = qrHtml;
	}
	
	defineExpose({
		genQr
	})
</script>

<style lang="scss" scoped>
	.qr {
		width: 300rpx;
		height: 300rpx;
	}
</style>